#!/usr/bin/env python
# coding:utf-8
import socket
import os
import sys
import re
from time import sleep
from json_parse import Jsonparse

CLRF = "\r\n"
PASSWORD_DIC=['redis','root','oracle','password','p@aaw0rd','abc123!','123456','admin']
VERBOSE = ['redis_version:4.', 'redis_version:5.']

class RemoteRedis():
    def __init__(self, rhost, rport, level):
        self.rhost = rhost
        self.rport = rport
        self.level = level
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.rhost, int(self.rport)))

    def check(self):
        """
            检测远程redis是否存在未授权访问或者弱口令
        """
        try:
            self.s.send("INFO" + CLRF)
            result = self.s.recv(1024)
            # print(result)
            if VERBOSE[0] in result or VERBOSE[1] in result:
                print("[+] The target host has unauthorized access, and there may be redis-rce vulnerability")
                exit(0)

            elif "NOAUTH" in result:
                print("[-] The target host requires a password to log in. There is no RedIS unauthorized")
                exit(1)
            
            else:
                print("[-] Not version 4.x or 5.x redis")
                exit(-1)

        except Exception as e:
            print(e)
            exit(-1)

def main(targetip, port, timeout):
    obj = RemoteRedis(targetip, port, timeout)
    obj.check()
    

if __name__ == '__main__':
    jsonfile = sys.argv[1] + '\\poc\\lib\\config.json'
    jsonobj = Jsonparse(jsonfile)
    jsondata = jsonobj.parse()
    targetip = sys.argv[2]
    timeout = jsondata['timeout1']
    port = sys.argv[3]
    socket.setdefaulttimeout(timeout)
    print("[*] Connecting to  {}:{}...".format(targetip, port))
    main(targetip, port, timeout)